package com.modules.service.sys.impl;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.common.util.ConstantUtil;
import com.common.vo.Result;
import com.modules.dao.sys.MenuDao;
import com.modules.dto.sys.resp.MenuEntityResp;
import com.modules.dto.sys.resp.RoleDtoResp;
import com.modules.entity.sys.MenuEntity;
import com.modules.entity.sys.RoleMenuEntity;
import com.modules.service.sys.MenuService;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;


/**
 * service菜单
 * @author Administrator
 *
 */
@Service
//@Transactional(rollbackFor = Exception.class)(readOnly = true) //全局事务（xml 如果配置了其他事务这里可以不用了）
public class MenuServiceImpl implements MenuService{

	@Autowired
	private MenuDao dao;
	
	
    /**
     * 查询
     * @param
     * @return
     */
    public Result<?> select(Page<MenuEntity> page, MenuEntity menu) {
        IPage<MenuEntity> iPage = dao.selectPage(page, new LambdaQueryWrapper<MenuEntity>());
        return Result.success(iPage.getRecords(), iPage.getTotal());
    }
    
	/**
	 * 获取树形表格
	 * @param m
	 * @return
	 */
	public Result<?> selecTreeTable(MenuEntity m) {
		List<MenuEntityResp> list = dao.selectTreeAll();
		if(StrUtil.isNotBlank(m.getMname())) {
			List<MenuEntityResp> resList = new ArrayList<MenuEntityResp>();
			for(MenuEntityResp menu : list) {
				if(menu.getMname().indexOf(m.getMname()) != -1) {
					resList.add(menu);
					for(MenuEntityResp menuTwo : list) {
						if(menuTwo.getParentId().equals(menu.getMid())) {
							resList.add(menuTwo);
						}
					}
				}
			}
			return Result.success(resList, (long)resList.size());
		}
		return Result.success(list, (long)list.size());
	}
	
	/**
	 * 保存
	 * @param menu
	 * @return
	 */
	@Transactional(rollbackFor = Exception.class)
	public Result<?> saveMenu(MenuEntity menu) {
		if(StrUtil.isEmpty(menu.getMname()) || StrUtil.isEmpty(menu.getCode())) {
			return Result.fail("参数错误");
		}
		LambdaQueryWrapper<MenuEntity> wrapper = new LambdaQueryWrapper<MenuEntity>();
		wrapper.eq(MenuEntity::getCode, menu.getCode());
		if(menu.getMid() != null) {
			wrapper.ne(MenuEntity::getMid, menu.getMid());
		}
		Integer exists = dao.selectCount(wrapper);
		if(exists > 0) {
			return Result.fail("编码重复，请重新输入");
		}
		// 主页只能有一个
		if(menu.getHomeState() == ConstantUtil.YES) {
			LambdaQueryWrapper<MenuEntity> queryWrapper = new LambdaQueryWrapper<MenuEntity>();
			if(menu.getMid() != null) {
				queryWrapper.ne(MenuEntity::getMid, menu.getMid());
			}
			queryWrapper.eq(MenuEntity::getIsProject, menu.getIsProject());
			MenuEntity m = new MenuEntity();
			m.setHomeState(ConstantUtil.NOT);
			dao.update(m, queryWrapper);
		}
		if(menu.getMid() == null) {
			dao.insert(menu);
		}else {
			dao.updateById(menu); 
		}
		return Result.success("保存成功");
	}
	
	/**
	 * 删除
	 * @param menu
	 * @return
	 */
	@Transactional(rollbackFor = Exception.class)
	public Result<?> delete(Integer mid) {
		dao.deleteById(mid);
		return Result.success("删除成功");
	}
	
	/**
	 * 更改状态
	 * @param menu
	 * @return
	 */
	@Transactional(rollbackFor = Exception.class)
	public Result<?> updateState(MenuEntity entity) {
		dao.updateById(entity);
		return Result.success();
	}
	
	/**
	 * 获取左侧菜单
	 * @param rid
	 * @return
	 */
	public Result<?> selectTree(Integer rid) {
		List<MenuEntityResp> list = dao.selectTree(rid);
		List<MenuEntityResp> resList = new ArrayList<MenuEntityResp>();
		for(MenuEntityResp menu : list) {
			if(menu.getParentId().equals(0)) {
				List<MenuEntityResp> children = selectTreeChildren(list, menu.getMid());
				menu.setChildren(children);
				resList.add(menu);
			}
		}
		return Result.success(resList, "获取成功");
	}
	
	public List<MenuEntityResp> selectTreeChildren(List<MenuEntityResp> list, int mid) {
		List<MenuEntityResp> resList = new ArrayList<MenuEntityResp>();
		if(list != null && list.size() > 0) {
			for(MenuEntityResp menu : list) {
				if(menu.getParentId().equals(mid)) {
					List<MenuEntityResp> child = selectTreeChildren(list, menu.getMid());
					menu.setChildren(child);
					resList.add(menu);
				}
			}
		}
		return resList;
	}
	
	/**
	 * 获取左侧菜单-All
	 * @param level
	 * @return
	 */
	public List<Map<String, Object>> selectTreeAll() {
		List<MenuEntityResp> list = dao.selectTreeAll();
		List<Map<String, Object>> resList = new ArrayList<>();
		for(MenuEntityResp menu : list) {
			if(menu.getParentId().equals(0)) {
				List<Map<String, Object>> child = selectTreeChildrendAll(list, menu.getMid());
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("id", menu.getMid());
				map.put("name", menu.getMname());
				map.put("open", true);
				if(CollUtil.isNotEmpty(child)) {
					map.put("children", child);
				}
				resList.add(map);
			}
		}
		List<Map<String, Object>> tempList = new ArrayList<>();
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("id", 0);
		map.put("name", "默认一级");
		map.put("open", true);
		map.put("children", resList);
		tempList.add(map);
		return tempList;
	}
	
	public List<Map<String, Object>> selectTreeChildrendAll(List<MenuEntityResp> list, int mid) {
		List<Map<String, Object>> resList = new ArrayList<Map<String, Object>>();
		if(list != null && list.size() > 0) {
			for(MenuEntityResp menu : list) {
				if(menu.getParentId().equals(mid)) {
					List<Map<String, Object>> child = selectTreeChildrendAll(list, menu.getMid());
					Map<String, Object> map = new HashMap<String, Object>();
					map.put("id", menu.getMid());
					map.put("name", menu.getMname());
					map.put("open", false);
					if(CollUtil.isNotEmpty(child)) {
						map.put("children", child);
					}
					map.put("checked", true);
					resList.add(map);
				}
			}
		}
		return resList;
	}

	/**
	 * 菜单选择角色
	 * @return
	 */
	@Override
	public Result<?> selectMenuRole(Integer mid) {
		List<RoleDtoResp> list = dao.selectMenuRole(mid);
		return Result.success(list, (long)list.size());
	}

	/**
	 * 保存菜单选择角色
	 * @return
	 */
	@Override
	public Result<?> saveMenuRole(Integer[] rids, Integer mid) {
		RoleMenuEntity roleMenu = new RoleMenuEntity();
		roleMenu.setMid(mid);
		dao.deleteRoleMenu(roleMenu);
		if(rids != null && rids.length > 0) {
			List<RoleMenuEntity> list = new ArrayList<>();
			for(Integer rid : rids) {
				RoleMenuEntity rm = new RoleMenuEntity(null, rid, mid, 1);// oid 没改先设置 1 了
				list.add(rm);
			}
			dao.insertRoleMenu(list);
		}
		return Result.success("授权成功");
	}
	
	
	
	
}
